<template>
  <div class="baseInfo" id="updataBj">
    <el-collapse accordion class="my-collapse" v-model="activeName">
      <el-collapse-item :title="title" name="baseINfo">
        <el-form :model="baseInfoForm" ref="baseInfoForm" label-width="120px" class="demo-dynamic">
          <!-- :rules="formItem.rules" :prop="'baseInfoData.'+formINdex+'.val'" -->
          <el-form-item
            v-for="(formItem, formINdex) in baseInfoForm.baseInfoData"
            :key="formINdex"
            :label="formItem.label"
            :rules="formItem.rules"
            :prop="formItem.type === 'tag'?'baseInfoData.'+formINdex+'.vm':'baseInfoData.'+formINdex+'.val'"
          >
            <!-- input  formItem.option.max-->
            <el-input
              size="mini"
              v-model="formItem.val"
              v-if="formItem.type === 'input'"
              :maxlength="formItem.option.max"
              :placeholder="formItem.placeholder"
              show-word-limit
              :disabled="mainOption.operate==='show'?true:false"
            ></el-input>
            <!-- 区域input -->
            <el-input
              size="mini"
              v-if="formItem.type === 'areaInput'"
              type="textarea"
              :autosize="{ minRows: 8, maxRows: 18}"
              :placeholder="formItem.placeholder"
              v-model="formItem.val"
              :maxlength="formItem.option.max"
              show-word-limit
              :disabled="mainOption.operate==='show'?true:false"
            ></el-input>
            <!-- 头图 button {{formItem.buttonText}} -->
            <div v-if="formItem.type === 'button'">
              <div>
                <el-button
                  type="warning"
                  size="mini"
                  class="el-icon-plus"
                  @click="openFile(formINdex)"
                ></el-button>
              </div>
              <el-image
                class="headIMg"
                v-show="formItem.val"
                :src="formItem.val"
                @click="avatarUpdata(formItem.val, formINdex)"
              ></el-image>
            </div>
            <!-- 数字 -->
            <el-input-number
              v-model="formItem.val"
              :precision="formItem.option.precision"
              :step="formItem.option.step"
              :min="1"
              :max="1000"
              size="mini"
              :disabled="mainOption.operate==='show'?true:false"
              v-if="formItem.type === 'number'"
            ></el-input-number>
            <!-- tag -->
            <div v-if="formItem.type === 'tag'" class="TagFlex">
              <el-tag
                :key="tag"
                v-for="tag in formItem.val"
                v-model="formItem.val"
                :closable="mainOption.operate==='show'?false:true"
                :disable-transitions="false"
                :type="formItem.tagType"
                @close="tagHandleClose(tag, formINdex)"
              >{{tag}}</el-tag>
              <div v-if="mainOption.operate !== 'show'">
                <el-input
                  class="input-new-tag"
                  v-if="formItem.TagInputVisible"
                  v-model="formItem.vm"
                  ref="saveTagInput"
                  size="small"
                  style="min-width: 200px;"
                  :placeholder="formItem.placeholder"
                  @keyup.enter.native="tagHandleInputConfirm(formINdex, formItem.label)"
                  @blur="tagHandleInputConfirm(formINdex, formItem.label)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showTagInput(formINdex)"
                >{{formItem.tagText}}</el-button>
              </div>
            </div>
            <!-- bool 切换     active-text="发布" inactive-text="不发布"-->
            <el-switch v-if="formItem.type === 'bool'" v-model="formItem.val" :disabled="mainOption.operate==='show'?true:false"></el-switch>
            <!-- 关联旅游产品选择 correlation 关联 -->
            <el-select
              v-if="formItem.type === 'option'"
              clearable
              size="mini"
              filterable
              multiple
              remote
              :remote-method="(query) => remoteMethod(formItem.name, query)"
              v-model="formItem.val"
              :placeholder="formItem.placeholder"
              style="width: 100%;"
              @change="(arr) => correlationChange(formINdex, arr)"
              v-loadmore="() => loadMore(formItem.name)"
              value-key="id"
              @visible-change="(bl) => visibleChange(formItem.name, bl, formINdex)"
              :disabled="mainOption.operate==='show'?true:false"
            >
              <div v-if="formItem.nowQuery">
                <el-option
                  v-for="(item) in formItem.searchArr"
                  :key="item.id"
                  :label="item.title"
                  :value="item"
                  :disabled="item.disabled"
                ></el-option>
              </div>
              <div v-else>
                <el-option
                  v-for="(item) in formItem.data"
                  :key="item.id"
                  :label="item.title"
                  :value="item"
                  :disabled="item.disabled"
                ></el-option>
              </div>
            </el-select>
            <!-- radioOption -->
            <el-select
              v-if="formItem.type === 'radioOption'"
              clearable
              size="mini"
              filterable
              remote
              :remote-method="(query) => remoteMethod(formItem.name, query)"
              v-model="formItem.val"
              :placeholder="formItem.placeholder"
              style="width: 100%;"
              @change="(arr) => correlationChange(formINdex, arr)"
              v-loadmore="() => loadMore(formItem.name)"
              value-key="id"
              @visible-change="(bl) => visibleChange(formItem.name, bl, formINdex)"
              :disabled="mainOption.operate==='show'?true:false"
            >
              <div v-if="formItem.nowQuery">
                <el-option
                  v-for="(item) in formItem.searchArr"
                  :key="item.id"
                  :label="item.title"
                  :value="item"
                  :disabled="item.disabled"
                ></el-option>
              </div>
              <div v-else>
                <el-option
                  v-for="(item) in formItem.data"
                  :key="item.id"
                  :label="item.title"
                  :value="item"
                  :disabled="item.disabled"
                ></el-option>
              </div>
            </el-select>
            <div v-show="formItem.type === 'radioOption'&&formItem.val.file_url&&formItem.val">
              <a
                :href="formItem.val.file_url"
                style="color: #409EFF;font-size: 11px;"
                target="view_window"
              >{{formItem.val.file_url}}</a>
            </div>
            <!-- map -->
            <div v-if="formItem.type === 'map'">
              <div>
                <el-input size="mini" style="width: 90%" v-model="formItem.region"></el-input>
                <el-input size="mini" style="width: 90%" v-model="formItem.pageCapacity"></el-input>
                <!-- @change="correlationChange(formItem.changeIf)" -->
                <el-input
                  clearable
                  size="mini"
                  filterable
                  v-model="formItem.val"
                  :placeholder="formItem.placeholder"
                  style="width: 90%;"
                  id="suggestId"
                >
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
              </div>
              <div id="scenicMap" style="width: 100%;height: 300px;"></div>
              {{formItem.option.longitude}},
              {{formItem.option.latitude}}
            </div>
            <!-- 电话 type="number" -->
            <el-input
              size="mini"
              v-if="formItem.type === 'numberInput'"
              :disabled="mainOption.operate==='show'?true:false"
              :placeholder="formItem.placeholder"
              @onkeyup="formItem.val=formItem.val.replace(/[^\d.]/g,'')"
              v-model.number="formItem.val"
              :maxlength="formItem.option.max"
              @input="(val) => numberInput(val, formINdex)"
              show-word-limit
            ></el-input>
          </el-form-item>
        </el-form>
      </el-collapse-item>
    </el-collapse>
    <!-- 全局裁剪       :dialog-img-add-num="dialogImgAddNum"        -->
    <dialog-img-edit
      :is-img-updata="isImgUpdata"
      :append-to-body="appendToBody"
      :Img-utils-title="ImgUtilsTitle"
      @img-url-transmit="imgUrlTransmit"
      :cropper-option-data="baseInfoCropperOption"
      ref="imgTextDialogImg"
    ></dialog-img-edit>
  </div>
</template>
<script>
const tool = require("../plugin/tool.js");
var checkTag = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("该项为必填项"));
  } else if (value.length > 8) {
    callback(new Error("不能超过8个字符"));
  } else {
    callback();
  }
};
// import tool from '../plugin/tool.js'

module.exports = {
  data() {
    return {
      loading: false,
      search: "",
      // 图片是否修改
      isImgUpdata: false,
      // 是否打开内层dialog
      appendToBody: false,
      arr: ["", "success", "info", "warning", "danger"],
      progress: 0,
      progressShow: false,
      // from的index
      formINdex: 0,
      // 添加图片状态
      addImg: false,
      ImgUtilsTitle: "添加图片",
      // 默认展开 baseINfo
      activeName: [],
      title: "基础信息",
      msg: "这是msg信息",
      clickMsg: "clickMsg"
      // storageList: Object.assign([], this.baseInfoForm.baseInfoData[8].data)
    };
  },
  props: {
    mainOption: {
      type: Object,
      default: () => {
        return {};
      }
    },
    baseInfoCropperOption: {
      type: Object,
      default: () => {
        return {};
      }
    },
    baseInfoForm: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  components: {
    "dialog-img-edit": httpVueLoader("./dialogImgEdit.vue")
  },
  created() {
    this.$watch(
      () => {
        const data =
          this.baseInfoForm.baseInfoData[8] &&
          this.baseInfoForm.baseInfoData[8].option
            ? this.baseInfoForm.baseInfoData[8].option
            : null;
        return data;
      },
      (now, old) => {
        // console.log("xr");
        this.$set(this.baseInfoForm.baseInfoData[8], "option", now);
      }
    );
  },
  mounted() {
    const mapShow =
      this.baseInfoForm.baseInfoData[8] &&
      this.baseInfoForm.baseInfoData[8].type === "map"
        ? true
        : false;
    mapShow
      ? this.$nextTick(() => {
          // this.mapInit();
          this.txMapInit();
        })
      : null;
  },
  methods: {
    numberInput(val, formINdex){
      this.baseInfoForm.baseInfoData[formINdex].val = val.replace(/[^\d]/g,'')
    },
    visibleChange(name, bl, index) {
      // console.log(name, bl, index, "blur");
      if (!bl) {
        this.baseInfoForm.baseInfoData[index].nowQuery = "";
      }
    },
    remoteMethod(name, query) {
      this.$emit("remote-method", { name, query });
    },
    // 加载更多
    loadMore(name) {
      this.$emit("scroll-more", name);
    },
    txMapInit() {
      let lat = this.baseInfoForm.baseInfoData[8].option.latitude;
      let lon = this.baseInfoForm.baseInfoData[8].option.longitude;
      let that = this;
      const markers = [];
      const center = new qq.maps.LatLng(lat, lon);
      const map = new qq.maps.Map(document.getElementById("scenicMap"), {
        center, // 地图的中心地理坐标。
        zoom: 15 // map缩放等级。
      });
      // 第一个标点
      var centerMarker = new qq.maps.Marker({
        position: center,
        map: map
      });
      // 监听map上的点击
      qq.maps.event.addListener(map, "click", function(event) {
        // 移除centerMarker点
        centerMarker.setMap(null);
        var mapClickAddmarker = new qq.maps.Marker({
          position: event.latLng,
          map: map
        });
        that.baseInfoForm.baseInfoData[8].option.latitude = event.latLng.lat;
        that.baseInfoForm.baseInfoData[8].option.longitude = event.latLng.lng;
        qq.maps.event.addListener(map, "click", function(event) {
          // 移除mapClickAddmarker点
          mapClickAddmarker.setMap(null);
        });
      });
      this.MapSearch(map, markers, that, centerMarker);
    },
    MapSearch(map, markers, that, centerMarker) {
      // const latlngBounds = new qq.maps.LatLngBounds();
      const searchService = new qq.maps.SearchService({
        // map,
        complete: function(results) {
          //设置回调函数参数
          var pois = results.detail.pois;
          var infoWin = new qq.maps.InfoWindow({
            map: map
          });
          var latlngBounds = new qq.maps.LatLngBounds();
          for (var i = 0, l = pois.length; i < l; i++) {
            var poi = pois[i];
            //扩展边界范围，用来包含搜索到的Poi点
            latlngBounds.extend(poi.latLng);
            (function(n) {
              var marker = new qq.maps.Marker({
                position: pois[n].latLng,
                map: map
              });
              marker.setTitle(i + 1);
              markers.push(marker);

              qq.maps.event.addListener(marker, "click", function() {
                console.log(pois[n], "pois[n]");
                infoWin.open();
                infoWin.setContent(
                  `<div style="width:280px;height:100px;">
                    ${
                      pois[n].name
                        ? `<div style="color: #00C0EF;font-size: 16px;margin: 10px 0;">${pois[
                            n
                          ].name || "暂无"}</div>`
                        : ""
                    }
                    ${
                      pois[n].address
                        ? `<div style="color: #37373D;font-size: 12px;margin: 5px 0;line-height: 1">地址: ${pois[
                            n
                          ].address || "暂无"}</div>`
                        : ""
                    }
                    ${
                      pois[n].phone
                        ? `<div style="color: #37373D;font-size: 12px;margin: 5px 0;line-height: 1">电话: ${pois[
                            n
                          ].phone || "暂无"}</div>`
                        : ""
                    }                   
                    ${
                      pois[n].category
                        ? `<div style="color: #37373D;font-size: 12px;margin: 5px 0;line-height: 1">种类: ${pois[
                            n
                          ].category || "暂无"}</div>`
                        : ""
                    }
                  </div>`
                );
                infoWin.setPosition(pois[n].latLng);
                that.baseInfoForm.baseInfoData[8].option.latitude =
                  pois[n].latLng.lat;
                that.baseInfoForm.baseInfoData[8].option.longitude =
                  pois[n].latLng.lng;
              });
            })(i);
          }
          //调整地图视野
          map.fitBounds(latlngBounds);
        }
      });
      const ap = new qq.maps.place.Autocomplete(
        document.getElementById("suggestId")
      );
      qq.maps.event.addListener(ap, "confirm", function(res) {
        centerMarker.setMap(null);
        markers.map((item, index) => {
          item.setMap(null);
        });
        const region = that.baseInfoForm.baseInfoData[8].region;
        const pageCapacity = that.baseInfoForm.baseInfoData[8].pageCapacity;
        searchService.setLocation(region); //设置默认检索范围（默认为全国），类型可以是坐标或指定的城市名称。
        // searchService.setPageIndex(pageIndex); //设置检索的特定页数。
        searchService.setPageCapacity(Number(pageCapacity)); //设置每页返回的结果数量。
        searchService.search(res.value);
        // searchService.setMap(map)
        that.baseInfoForm.baseInfoData[8].val = searchService.keyword;
        console.log(searchService, "searchService");
      });
    },
    unique(arr) {
      const res = new Map();
      return arr.filter(arr => !res.has(arr.id) && res.set(arr.id, 1));
    },
    correlationChange(index, changeArr) {
      // console.log('.baseInfoForm.baseInfoData[9].data')
      // this.baseInfoForm.baseInfoData[9].data = this.storageList
      // 关联旅游
      // if (changeStr === "travel") {
      // } else {
      //   // 关联活动
      // }
      // this.baseInfoForm.baseInfoData[index].data = Array.from(
      //   new Set(this.baseInfoForm.baseInfoData[index].data.concat(changeArr))
      // );
      this.baseInfoForm.baseInfoData[index].data = this.unique(
        this.baseInfoForm.baseInfoData[index].data.concat(changeArr)
      );
    },
    runFormConfirm() {
      let that = this;
      let result = allCheckRules(that, "baseInfoForm");
      Promise.all([result])
        .then(() => {
          console.log("baseINfo 验证ok");
        })
        .catch(() => {
          console.log("baseINfo 验证closer");
          that.activeName = "baseINfo";
        });
      return result;
    },
    avatarUpdata(url, index) {
      if (this.mainOption.operate !== "show") {
        this.formINdex = index;
        this.isImgUpdata = true;
        this.baseInfoCropperOption.img = url;
        this.ImgUtilsTitle = "裁剪图片";
        this.$refs.imgTextDialogImg.addImg = true;
      }
    },
    imgUrlTransmit(imgurl, isImgUpdata) {
      let headImg = this.baseInfoForm.baseInfoData[this.formINdex];
      headImg.val = imgurl;
    },
    // 打开文件
    openFile(formINdex) {
      if (this.mainOption.operate !== "show") {
        this.formINdex = formINdex;
        this.isImgUpdata = false;
        this.$refs.imgTextDialogImg.$refs.myInput.value = "";
        this.$refs.imgTextDialogImg.$refs.myInput.click();
        this.ImgUtilsTitle = "添加图片";
      }
    },
    // 显示tag input框
    showTagInput(formINdex) {
      let tag = this.baseInfoForm.baseInfoData[formINdex];
      tag.vm = "";
      tag.TagInputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput[0].$refs.input.focus();
      });
    },
    // tag添加
    tagHandleInputConfirm(formINdex, name) {
      const Tag = this.baseInfoForm.baseInfoData[formINdex];
      let inputValue = Tag.vm;
      if (inputValue.length > 8 || inputValue === "") {
        return;
      }
      const checkResult = Tag.val.some((value, index, array) => {
        return value === inputValue;
      });
      if (inputValue) {
        if (!checkResult) {
          Tag.val.push(inputValue);
        }
      }
      Tag.TagInputVisible = false;
      // Tag.vm = "";
    },
    // tag移除
    tagHandleClose(tag, formINdex) {
      const Tag = this.baseInfoForm.baseInfoData[formINdex].val;
      Tag.splice(Tag.indexOf(tag), 1);
    }
  }
};
</script>
<style scoped>
.headIMg {
  padding: 6px;
  border: 1px solid #ddd;
  box-shadow: 1px 1px 5px 0 #a2958a;
}
.baseInfo {
  width: 90%;
}
.button-new-tag {
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  vertical-align: bottom;
}
.TagFlex .el-tag {
  margin-right: 10px;
}
.my-collapse .el-collapse-item__header {
  margin-left: 30px;
}
#updataBj .el-collapse-item__wrap {
  background: transparent;
}
#updataBj .el-collapse-item__header {
  background: transparent;
}
</style>